package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
)

type Msg struct {
	key     string
	content string
}

func proxy_handler(key string, url string, msg_chan chan Msg) {
	log.Println(url)
	resp, e := http.Get(url)
	if e != nil {
		log.Println(e)
	}
	defer resp.Body.Close()
	content, _ := ioutil.ReadAll(resp.Body)
	log.Println("rpc_res")
	log.Println(string(content))
	msg := Msg{key, string(content)}
	msg_chan <- msg
}

func blender_handler(rw http.ResponseWriter, req *http.Request) {
	msg_chan := make(chan Msg)
	request := map[string]string{}
	decoder := json.NewDecoder(req.Body)
	_ = decoder.Decode(&request)
	log.Println("request")
	log.Println(request)
	log.Println("key")
	for key, url := range request {
		log.Println("key")
		log.Println(key)
		go proxy_handler(key, url, msg_chan)
	}
	size := len(request)
	response := map[string]string{}
	log.Println(size)
	var _msg Msg
	for i := 0; i < size; i++ {
		_msg = <-msg_chan
		response[_msg.key] = _msg.content
	}
	rw.Header().Set("Content-Type", "application/json")
	res_json, _ := json.Marshal(response)
	log.Println("response")
	log.Println(string(res_json))
	fmt.Fprint(rw, string(res_json))
}

func main() {
	http.HandleFunc("/blender", blender_handler)
	log.Fatal(http.ListenAndServe(":10022", nil))
}
